package com.blockchain.front;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.blockchain.framework.resource.ResourceProvider;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.variables.P2PConst;
import com.cuohe.models.BuyEntity;
import com.cuohe.models.SellEntity;
import com.cuohe.service.MakeMatchService;

/**
 * 容器起动后去启动撮合
 *
 */
@SuppressWarnings("unused")
@WebListener()
public class StartMatchListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public StartMatchListener() {
        
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
    	
    }

	/**
	 * 容器起动时向数据库拿需要的撮合数据
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0) {
    	/*ResourceProvider resourceProvider = ResourceRegister.getResourceProvider(arg0.getServletContext());
    	
    	MakeMatchService mms = resourceProvider.getResource(ServiceProvider.class).createServiceSession()
				.getService(MakeMatchService.class);
    	
		try {
			Connection con = mms.getCon(P2PConst.DB_USER);
			
			//所有交易中的买卖KEY
			Integer[] t6017F01 = getAllT6017F01(resourceProvider,mms,con);
			TreeSet<Integer> ts = new TreeSet<Integer>(Arrays.asList(t6017F01));
			
			//买数据
			TreeMap<Integer, BuyEntity> buyMap = getBuyData(mms, con);
			
			//卖数据
			TreeMap<Integer,SellEntity> sellMap = getSellData(mms, con);
			
			MakeMatch match = MakeMatch.getInstance(resourceProvider, ts, buyMap, sellMap);
			arg0.getServletContext().setAttribute("CHUANGKE_MATCH", match);
			
			System.out.println("==============开始运行撮合程序=====================>");			
			Timer t = new Timer();
			t.schedule(match, 1000,2000);	
			
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}*/
    }

    /**
     * 组装卖数据
     * */
	private TreeMap<Integer,SellEntity> getSellData(MakeMatchService mms, Connection con) throws SQLException {
		SellEntity[] sells = mms.selectA(con, new ArrayParser<SellEntity>() {

			@Override
			public SellEntity[] parse(ResultSet rs) throws SQLException {
				ArrayList<SellEntity> list = new ArrayList<SellEntity>();
				while(rs.next()) {
					SellEntity sell = new SellEntity();
					sell.setId(rs.getInt(1));
					sell.setMarketID(rs.getInt(2));
					sell.setUserID(rs.getInt(3));
					sell.setPrice(rs.getDouble(4));
					sell.setSellNum(rs.getDouble(5));
					sell.setDealNum(rs.getDouble(6));
					sell.setSellTime(rs.getTimestamp(9));
					sell.setDealPrice(rs.getDouble(11));
					list.add(sell);
				}
				return list == null ? null : list.toArray(new SellEntity[list.size()]);
			}}, "select * from t6017 where F07='MC' AND F08='JYZ' AND F05-F06>0 ORDER BY F04 ASC, f09 ASC");
		
		final Map<Integer,SellEntity> sellMap = new HashMap<Integer,SellEntity>();
		for(SellEntity se:sells) {
			sellMap.put(se.getId(), se);
		}
		
		TreeMap<Integer,SellEntity> sellMapTree = new TreeMap<Integer,SellEntity>(new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				int tempI = 0;
				if(sellMap.get(o1)==null||sellMap.get(o2)==null) return -1;
				double price = sellMap.get(o1).getPrice()-sellMap.get(o2).getPrice();
				if(price!=0) {
					tempI = (price>0)?2:-1;
				}else {
					price = sellMap.get(o1).getSellTime().compareTo(sellMap.get(o2).getSellTime());
					if(price!=0) {
						tempI = (price>0)?1:-1;
					}
				}		
				return tempI;
				
			}
		});
		sellMapTree.putAll(sellMap);
		return sellMapTree;
	}
    
    /**
     *  组装买数据
     * */
	private TreeMap<Integer, BuyEntity> getBuyData(MakeMatchService mms, Connection con) throws SQLException {
		BuyEntity[] buys = mms.selectA(con, new ArrayParser<BuyEntity>() {

			@Override
			public BuyEntity[] parse(ResultSet rs) throws SQLException {
				ArrayList<BuyEntity> list = new ArrayList<BuyEntity>();
				while(rs.next()) {
					BuyEntity buy = new BuyEntity();
					buy.setId(rs.getInt(1));
					buy.setMarketID(rs.getInt(2));
					buy.setUserID(rs.getInt(3));
					buy.setPrice(rs.getDouble(4));
					buy.setBuyNum(rs.getDouble(5));
					buy.setDealNum(rs.getDouble(6));
					buy.setBuyTime(rs.getTimestamp(9));
					buy.setDealPrice(rs.getDouble(11));
					list.add(buy);
				}
				return list == null ? null : list.toArray(new BuyEntity[list.size()]);
			}}, "select * from t6017 where F07='MR' AND F08='JYZ' AND F05-F06>0 ORDER BY F04 DESC, f09 ASC");
		
		final Map<Integer,BuyEntity> map = new HashMap<Integer,BuyEntity>();
		for(BuyEntity be:buys) {
			map.put(be.getId(), be);
		}
		
		TreeMap<Integer,BuyEntity> buyMap = new TreeMap<Integer,BuyEntity>(new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) { 
				int tempI = 0;
				if(map.get(o1)==null||map.get(o2)==null) return -1;
				double price = map.get(o2).getPrice()-map.get(o1).getPrice();
				if(price!=0) {
					tempI = (price>0)?2:-1;
				}else {
					price = map.get(o2).getBuyTime().compareTo(map.get(o1).getBuyTime());
					if(price!=0) {
						tempI = (price<0)?1:-1;
					}
				}
				
				return tempI;				
			
			}
		});
		buyMap.putAll(map);
		return buyMap;
	}
	
	/**
	 * 获取买卖的KEY
	 * */
	private Integer[] getAllT6017F01(ResourceProvider resourceProvider,MakeMatchService mms, Connection con) throws SQLException {		
		
		return mms.selectA(con, new ArrayParser<Integer>() {

			@Override
			public Integer[] parse(ResultSet rs) throws SQLException {
				ArrayList<Integer> list = new ArrayList<Integer>();
				while(rs.next()) {				
					list.add(rs.getInt(1));
				}
				return list == null ? null : list.toArray(new Integer[list.size()]);
			}
		}, "select * from "+P2PConst.DB_USER+".t6017 where F08='JYZ' ORDER BY f09 ASC");		

	}
	
}
